package cn.coder.toolkit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author com.mrathena on 2019/5/27 11:16
 */
public final class CloneKit {

	private CloneKit() {}

	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T clone(T object) throws IOException, ClassNotFoundException {
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			 ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
			 ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
			objectOutputStream.writeObject(object);
			return (T) objectInputStream.readObject();
		}
	}

}
